package org.zyl.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class BeanUtil {
	public static Map<String,Object> beanToMap(Object parameter) {
		Map<String,Object> param = new HashMap<String,Object>();
		
		if (parameter == null)
			return null;
		Class<?> cl;
		try {
			cl = Class.forName(parameter.getClass().getName());
			for (Field field : cl.getDeclaredFields()) { // 得到该类下所有属性
				String getMethodName = "get" + toFirstLetterUpperCase(field.getName());
				param.put(field.getName(), parameter.getClass().getMethod(getMethodName).invoke(parameter));
			}
		} catch (IllegalArgumentException | SecurityException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return param;
	}

	public static String toFirstLetterUpperCase(String str) {
		if (str == null || str.length() < 2) {
			return str;
		}
		String firstLetter = str.substring(0, 1).toUpperCase();
		return firstLetter + str.substring(1, str.length());
	}
}